<template>
  <!-- 外部展示部分  -->
  <div class="coupon-discount-container">
    <!-- 优惠卷 弹窗按钮 -->
    <div class="appoint_ment_coupon" @click="showCouponPopup = true">
      <div class="appoint_ment_coupon_l">
        <img :src="couponIcon" alt="" />
        <span>Coupon/Discount({{ couponDiscountCount }})</span>
      </div>
      <div class="appoint_ment_coupon_r">
        <span v-if="hasActiveDiscount" class="pricecolor">{{
          discountAmountText
        }}</span>
      </div>
    </div>
    <!-- 优惠后的价格 -->
    <div class="appoint_ment_price">
      <div class="appoint_ment_price_l">
        <span>Total order price</span>
      </div>
      <div class="appoint_ment_price_r">
        <span class="pricecolor">C${{ finalPrice }}</span>
        <div
          class="appoint_ment_price_r_tips pricecolor"
          v-if="hasActiveDiscount"
        >
          Discounted by {{ discountAmountText }}
        </div>
      </div>
    </div>
    <!-- 优惠卷弹窗 -->
    <van-popup
      v-model:show="showCouponPopup"
      round
      position="bottom"
      style="height: 90%"
      closeable
    >
      <!-- 手动添加标题 -->
      <div class="popup_header">
        <h3>Select Coupon</h3>
      </div>
      <!-- 优惠券列表 -->
      <div class="popup_body">
        <!-- 输入框 -->
        <div class="popup_input">
          <input
            placeholder="Enter coupon code"
            class="popup_input_search"
            type="text"
            v-model="couponCode"
          />
          <button @click="applyCouponCode" class="popup_input_btn">
            Apply
          </button>
        </div>
        <!-- Coupon -->
        <div class="Coupon">
          <div class="Coupon_title">
            <p>Coupon</p>
          </div>
          <van-radio-group v-model="selectedCoupon">
            <div
              v-for="item in coupons"
              :key="item.id"
              class="Coupon_list_item"
              :class="{
                CouponClass: selectedCoupon === item.id,
                'disabled-item': item.isExpired,
              }"
              @click="toggleCoupon(item.id)"
            >
              <div class="Coupon_list_item_price">
                C$<span>{{ item.value }}</span>
              </div>
              <div class="Coupon_list_item_info">
                <b>{{ item.title }}</b>
                <p>{{ item.validDate }}</p>
                <p>{{ item.description }}</p>
              </div>
              <van-radio
                :name="item.id"
                checked-color="#18b792"
                icon-size="16px"
              />
            </div>
          </van-radio-group>
        </div>
        <!-- Discount -->
        <div class="Coupon Discount">
          <div class="Coupon_title">
            <p>Discount</p>
          </div>
          <van-radio-group v-model="selectedDiscount">
            <div
              v-for="item in discounts"
              :key="item.id"
              class="Coupon_list_item"
              :class="{ CouponClass: selectedDiscount === item.id }"
              @click="toggleDiscount(item.id)"
            >
              <div class="Coupon_list_item_price">
                <span>{{ item.value }}%</span>
              </div>
              <div class="Coupon_list_item_info">
                <b>{{ item.title }}</b>
                <p>{{ item.validDate }}</p>
                <p>{{ item.description }}</p>
              </div>
              <van-radio
                :name="item.id"
                checked-color="#18b792"
                icon-size="16px"
              />
            </div>
          </van-radio-group>
        </div>

        <!-- Submit -->
        <van-button round color="#1ab692" @click="handleSubmit"
          >Submit</van-button
        >
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { showToast } from "vant";
// 初始化选择最优优惠
const initBestDiscount = () => {
  const best = calculateBestDiscount();
  let couponInfo = null;

  if (best) {
    if (best.type === "coupon") {
      const coupon = coupons.value.find((item) => item.id === best.id);
      selectedCoupon.value = best.id;
      couponInfo = {
        type: "coupon",
        code: coupon?.code || null,
        value: coupon?.value,
        addCode: false, // 标记为默认选择
      };
    } else {
      const discount = discounts.value.find((item) => item.id === best.id);
      selectedDiscount.value = best.id;
      couponInfo = {
        type: "discount",
        code: discount?.code || null,
        value: discount?.value,
        addCode: false,
      };
    }
    emit("couponApplied", couponInfo); // 通知父组件
  }
  return couponInfo;
};

// 暴露方法给父组件
defineExpose({
  openCouponPopup: () => {
    showCouponPopup.value = true;
  },
  initBestDiscount, // 新增
});

// 定义 Props 类型
const props = defineProps({
  baseprice: {
    type: Number,
    required: true,
    validator: (value) => value >= 0,
  },
});

// 定义 Emits 事件
const emit = defineEmits(["updatetotalPrice", "couponApplied"]);

// ========== UI 控制状态 ==========
const showCouponPopup = ref(false); // 控制优惠券弹窗显示
const couponCode = ref(""); // 用户输入的优惠码

// ========== 优惠券数据 ==========
/**
 * 优惠券数据结构:
 * @property {number} id - 唯一标识
 * @property {number} value - 优惠金额或折扣比例
 * @property {'fixed'|'percentage'} type - 优惠类型
 * @property {string} title - 优惠券标题
 * @property {string} validDate - 有效期
 * @property {string} description - 描述
 * @property {boolean} isExpired - 是否过期
 */
const generateRandomId = () => {
  return Date.now() + Math.floor(Math.random() * 1000);
};
const coupons = ref([
  {
    id: generateRandomId(),
    value: 100,
    code: "334960",
    type: "fixed",
    title: "For XXXX only",
    validDate: "7/7/2023-7/12/2023",
    description: "Check out the rules",
    isExpired: false,
  },
]);

/**
 * 折扣数据结构 (与优惠券类似)
 */
const discounts = ref([
  {
    id: generateRandomId(),
    value: 95,
    code: "000000",
    type: "percentage",
    title: "For XXXX only",
    validDate: "7/7/2023-7/12/2023",
    description: "Check out the rules",
    isExpired: false,
  },
]);
// 提供用户输入码

// ========== 选择状态 ==========
const selectedCoupon = ref(null); // 当前选中的优惠券ID
const selectedDiscount = ref(null); // 当前选中的折扣ID

// ========== 静态资源 ==========
const couponIcon = new URL("../assets/Coupon.png", import.meta.url).href;

// ========== 计算属性 ==========
// 优惠券和折扣总数
const couponDiscountCount = computed(
  () => coupons.value.length + discounts.value.length
);

// 是否有激活的优惠
const hasActiveDiscount = computed(
  () => selectedCoupon.value !== null || selectedDiscount.value !== null
);
// 折扣金额文本显示
const discountAmountText = computed(() => {
  if (selectedCoupon.value) {
    const coupon = coupons.value.find(
      (item) => item.id === selectedCoupon.value
    );
    return `-C$${coupon?.value || 0}`;
  }
  if (selectedDiscount.value) {
    const discount = discounts.value.find(
      (item) => item.id === selectedDiscount.value
    );
    return `-${discount?.value || 0}%`;
  }
  return "";
});

// 计算最终价格
const finalPrice = computed(() => {
  let price = props.baseprice;

  if (selectedCoupon.value) {
    const coupon = coupons.value.find(
      (item) => item.id === selectedCoupon.value
    );
    if (coupon) {
      price =
        coupon.type === "fixed"
          ? price - coupon.value
          : price * (1 - coupon.value / 100);
    }
  } else if (selectedDiscount.value) {
    const discount = discounts.value.find(
      (item) => item.id === selectedDiscount.value
    );
    if (discount) {
      price *= discount.value / 100;
    }
  }

  // 确保价格不低于0
  return Math.max(0, price.toFixed(2));
});

// ========== 监听器 ==========
// 当最终价格变化时通知父组件
watch(finalPrice, (newValue) => {
  emit("updatetotalPrice", parseFloat(newValue));
});

// ========== 方法 ==========

// 提供优惠劵码
// 1. 定义独立优惠码数据库（数字6位）
const promotionCodes = {
  // 优惠券码
  123456: {
    type: "coupon",
    value: 100,
    title: "新用户专享券",
    validDate: "2023-12-31",
    description: "满500元可用",
  },
  // 折扣码
  654321: {
    type: "discount",
    value: 90, // 9折
    title: "限时折扣",
    validDate: "2023-11-30",
    description: "全品类通用",
  },
};
/**
 * 应用优惠码
 */
// 2. 优惠码验证方法
const applyCouponCode = () => {
  const inputCode = couponCode.value.trim();
  const addCode = ref(true);
  // 验证6位数字
  if (!/^\d{6}$/.test(inputCode)) {
    showToast("请输入6位数字优惠码");
    return;
  }

  // 查找匹配的优惠码
  const promotion = promotionCodes[inputCode];
  if (!promotion) {
    showToast("优惠码无效");
    return;
  }

  // 3. 动态添加到对应列表
  if (promotion.type === "coupon") {
    const newCoupon = {
      id: Date.now(), // 生成唯一ID
      code: inputCode,
      value: promotion.value,
      type: "fixed",
      title: promotion.title,
      validDate: promotion.validDate,
      description: promotion.description,
      isExpired: false,
    };
    coupons.value.push(newCoupon);
    selectedCoupon.value = newCoupon.id;
    selectedDiscount.value = null;
  } else {
    const newDiscount = {
      id: Date.now(),
      code: inputCode,
      value: promotion.value,
      type: "percentage",
      title: promotion.title,
      validDate: promotion.validDate,
      description: promotion.description,
      isExpired: false,
    };
    discounts.value.push(newDiscount);
    selectedDiscount.value = newDiscount.id;
    selectedCoupon.value = null;
  }

  showToast("优惠码已应用");
  couponCode.value = "";
  emit("couponApplied", { code: inputCode, addCode: addCode.value });
};

/**
 * 切换优惠券选择
 * @param {number} id - 优惠券ID
 */
const toggleCoupon = (id) => {
  selectedCoupon.value = selectedCoupon.value === id ? null : id;
  if (selectedCoupon.value) selectedDiscount.value = null;
};

/**
 * 切换折扣选择
 * @param {number} id - 折扣ID
 */
const toggleDiscount = (id) => {
  selectedDiscount.value = selectedDiscount.value === id ? null : id;
  if (selectedDiscount.value) selectedCoupon.value = null;
};

/**
 * 提交优惠选择
 */
// 修改handleSubmit方法
// 定义一个标志变量，用于判断是否是用户手动提交
const isManualSubmit = ref(true);
const handleSubmit = () => {
  showCouponPopup.value = false;

  // 准备传递给父组件的数据
  let couponInfo = null;

  if (selectedCoupon.value) {
    const coupon = coupons.value.find(
      (item) => item.id === selectedCoupon.value
    );
    couponInfo = {
      type: "coupon",
      id: selectedCoupon.value,
      code: coupon?.code || null, // 传递默认优惠券的 code
      value: coupon?.value,
    };
  } else if (selectedDiscount.value) {
    const discount = discounts.value.find(
      (item) => item.id === selectedDiscount.value
    );
    couponInfo = {
      type: "discount",
      id: selectedDiscount.value,
      code: discount?.code || null, // 传递默认折扣的 code
      value: discount?.value,
    };
  }

  // 通知父组件
  emit("couponApplied", couponInfo, isManualSubmit.value);
};
// 新增计算最优优惠方法
const calculateBestDiscount = () => {
  const basePrice = props.baseprice;
  // 找出所有有效优惠（未过期的）
  const validCoupons = coupons.value.filter((c) => !c.isExpired);
  const validDiscounts = discounts.value.filter((d) => !d.isExpired);

  // 计算每种优惠的最终价格
  const calculatePrice = (item) => {
    return item.type === "fixed"
      ? basePrice - item.value
      : basePrice * (item.value / 100);
  };

  // 找出最优优惠券
  const bestCoupon =
    validCoupons.length > 0
      ? validCoupons.reduce((best, current) =>
          calculatePrice(current) < calculatePrice(best) ? current : best
        )
      : null;

  // 找出最优折扣
  const bestDiscount =
    validDiscounts.length > 0
      ? validDiscounts.reduce((best, current) =>
          calculatePrice(current) < calculatePrice(best) ? current : best
        )
      : null;

  // 比较两种优惠方式
  if (bestCoupon && bestDiscount) {
    return calculatePrice(bestCoupon) < calculatePrice(bestDiscount)
      ? { type: "coupon", id: bestCoupon.id }
      : { type: "discount", id: bestDiscount.id };
  } else if (bestCoupon) {
    return { type: "coupon", id: bestCoupon.id };
  } else if (bestDiscount) {
    return { type: "discount", id: bestDiscount.id };
  }

  return null;
};
</script>

<style lang="less" scoped>
/* 样式保持不变 */
.appoint_ment_coupon {
  border-radius: 10px;
  padding: 0 10px;
  margin-top: 10px;
  height: 45px;
  background: linear-gradient(20deg, #fff4e4, #fff);
  font-size: 15px;
  font-weight: 460;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .appoint_ment_coupon_l {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .appoint_ment_coupon_r {
    width: 100px;
    height: 20px;
    position: relative;
    line-height: 20px;
    text-align: right;
    padding-right: 8px;
    &::before {
      content: "";
      position: absolute;
      top: 50%;
      right: 3px;
      width: 4px;
      height: 4px;
      border: 2px solid #6f7376;
      border-left: 0;
      border-bottom: 0;
      transform: translateY(-50%) rotate(45deg);
    }
    span {
      white-space: nowrap;
      font-size: 14px;
    }
  }
}

.appoint_ment_price {
  background-color: #fff;
  border-radius: 10px;
  padding: 0 10px;
  margin-top: 10px;
  height: 45px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .appoint_ment_price_r {
    text-align: right;
    .appoint_ment_price_r_tips {
      font-size: 12px;
    }
  }
}

.van-popup {
  .popup_header {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 12px;
    border-bottom: 1px solid #eee;
    .popup_header h3 {
      font-size: 18px;
    }
  }
  .popup_body {
    padding: 10px;
    .popup_input {
      position: relative;
      .popup_input_search {
        width: 100%;
        height: 40px;
        outline: none;
        border: none;
        border: 1px solid #ccc;
        padding-left: 10px;
        box-sizing: border-box;
        border-radius: 5px;
        &::placeholder {
          color: #ccc;
          font-size: 16px;
        }
      }
      .popup_input_btn {
        position: absolute;
        right: 10px;
        top: 0;
        height: 40px;
        border: none;
        background-color: transparent;
        font-size: 15px;
        color: #1ab692;
        font-weight: bold;
      }
    }
    .Coupon {
      padding: 10px 0;
      .Coupon_title {
        font-size: 15px;
        font-weight: bold;
      }
      .van-radio-group {
        display: flex;
        flex-direction: column;
        align-items: center;
        .Coupon_list_item {
          width: 100%;
          border-radius: 5px;
          box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
          padding: 8px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          margin-top: 12px;

          .Coupon_list_item_price {
            font-weight: bold;
            font-size: 16px;
            span {
              font-size: 20px;
            }
          }
          .Coupon_list_item_info {
            margin-left: 40px;
            p {
              font-size: 12px;
              color: #ccc;
            }
          }
          .van-radio {
            margin-left: auto;
            border: 1.5px solid #ccc;
            border-radius: 50%;
          }
          &.CouponClass {
            border: 2px solid #1ab692;
            .van-radio {
              border: none;
            }
          }
        }
      }
      &.Discount {
        margin-bottom: 100px;
      }
    }
    .van-button {
      width: 90%;
      height: 45px;
      position: fixed;
      left: 50%;
      bottom: 15px;
      transform: translateX(-50%);
      font-weight: bold;
    }
  }
}
</style>